package com.excesys.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.excesys.mapper.ProductOrderMapper;
import com.excesys.pojo.ProductOrder;
import com.excesys.service.AliPayService;
import com.excesys.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@RestController
public class AliPayController {

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private ProductOrderMapper productOrderMapper;

    /**
     * 进入支付主页
     *
     * @return
     */
    @GetMapping("/")
    public ModelAndView index() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("testAliPay");
        return mav;
    }

    /**
     * 提交订单
     *
     * @param subject
     * @param totalAmount
     * @return
     * @throws AlipayApiException
     */
    @PostMapping("/order/alipay")
    public String aliPay(String subject, Double totalAmount) throws AlipayApiException {
        System.out.println("--------进入提交支付----------");
        ProductOrder order = new ProductOrder();
        order.setOut_trade_no(IdUtil.getSnowflakeNextIdStr());
        order.setSubject(subject);
        order.setTotal_amount(totalAmount);
        order.setCreate_time(LocalDateTime.now());
        productOrderMapper.insert(order);
        //同时将订单信息存入redis并设置过期时间
        redisUtils.set(order.getOut_trade_no(), order, 60);
        //如果在过期时间内订单未支付则删除redis中的订单信息
        System.out.println("order-----:" + order);
        return aliPayService.aliPay(order);
    }

    /**
     * 支付成功
     *
     * @return
     */
    @GetMapping("/paySuccess")
    public ModelAndView paySuccess(HttpServletRequest request) {
        System.out.println("--------支付成功----------");
        //如果支付成功，订单就要新增到数据库
        //如果取消支付，也要新增订单到数据库，取消订单-状态
        //订单查询能够查出订单状态 信息
        String out_trade_no = request.getParameter("out_trade_no");
        UpdateWrapper uw = new UpdateWrapper();
        uw.eq("out_trade_no", out_trade_no);
        uw.set("order_status", 1);
        int flag = productOrderMapper.update(new ProductOrder(), uw);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("out_trade_no", out_trade_no);
        modelAndView.setViewName("success");
        System.out.println("支付成功" + flag);
        return modelAndView;
    }

}

